package kr.hkit.androidproject_caloriecheck;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DAO {
	private DBHelper helper;
	private SQLiteDatabase db;

	private DAO(Context context) {
		helper = new DBHelper(context);
		db = helper.getWritableDatabase();
	}

	public static DAO open(Context context) {
		return new DAO(context);
	}

	public void close() {
		helper.close();
	}
	
	public boolean foodInsert(String name, int kcal) {
		String sql = "insert into food values(" + "null, " + "'" + name + "'," +" '" + kcal + "');";
		try {
			db.execSQL(sql);
		} catch (SQLException e) {
			return false;
		}
		return true;
	}
	
	public ArrayList<MyItem> foodSelectAll(){
		ArrayList<MyItem> arList = new ArrayList<>();
		MyItem food;
		
		String sql = "select food, foodkcal from food;";
		Cursor cursor = db.rawQuery(sql, null);
		
		while(cursor.moveToNext()){
			String name = cursor.getString(0);
			int kcal = cursor.getInt(1);
			food = new MyItem(name, kcal);
			arList.add(food);
		}	
		return arList;
	}
	
	public ArrayList<MyItem> foodSelectByName(String foodname){
		ArrayList<MyItem> arList = new ArrayList<>();
		MyItem food;
		
		String sql = "select food, foodkcal from food where food like'%" + foodname + "%';";
		Cursor cursor = db.rawQuery(sql, null);
		
		while(cursor.moveToNext()){
			String name = cursor.getString(0);
			int kcal = cursor.getInt(1);
			food = new MyItem(name, kcal);
			arList.add(food);
		}
		return arList;
	}
	
	public boolean exerciseInsert(String name, int kcal) {
		String sql = "insert into exercise values(" + "null, " + "'" + name + "'," +" '" + kcal + "');";
		try {
			db.execSQL(sql);
		} catch (SQLException e) {
			return false;
		}
		return true;
	}
	
	public ArrayList<MyItem> exerciseSelectAll(){
		ArrayList<MyItem> arList = new ArrayList<>();
		MyItem exercise;
		
		String sql = "select exercise, exercisekcal from exercise;";
		Cursor cursor = db.rawQuery(sql, null);
		
		while(cursor.moveToNext()){
			String name = cursor.getString(0);
			int kcal = cursor.getInt(1);
			exercise = new MyItem(name, kcal);
			arList.add(exercise);
		}	
		return arList;
	}
	
	public ArrayList<MyItem> exerciseSelectByName(String exercisename){
		ArrayList<MyItem> arList = new ArrayList<>();
		MyItem exercise;
		
		String sql = "select exercise, exercisekcal from exercise where exercise like'%" + exercisename + "%';";
		Cursor cursor = db.rawQuery(sql, null);
		
		while(cursor.moveToNext()){
			String name = cursor.getString(0);
			int kcal = cursor.getInt(1);
			exercise = new MyItem(name, kcal);
			arList.add(exercise);
		}
		return arList;
	}
}
